package dao

import (
	"github.com/topfreegames/pitaya/fairy/pojo"
	"github.com/topfreegames/pitaya/logger"
	"sync"
)

var (
	AccountDataDao *accountDataDao
	accountDataDaoOnce sync.Once
)

type accountDataDao struct {
	BaseDao
}

func NewAccountDataDao() *accountDataDao {
	accountDataDaoOnce.Do(func() {
		AccountDataDao = &accountDataDao{}
	})
	return AccountDataDao
}

func (p *accountDataDao) GetAccountDataByUsernameAndChannelIdAndAppId(username,channelId,appId string) (*pojo.AccountData,error) {
	accountData := &pojo.AccountData{}
	has,err := p.enginer.Where("username=? and channelId=? and appId=?",username,channelId,appId).Get(accountData)
	if err != nil{
		logger.Log.Errorf("GetAccountDataByUsernameAndChannelIdAndAppId error:%s",err.Error())
		return nil,err
	}

	if !has{
		return nil,nil
	}


	return accountData,nil
}

func (p *accountDataDao) GetAccountDataByUsernameAndChannelId(username,channelId string) ([]*pojo.AccountData,error) {
	accountDatas := make([]*pojo.AccountData,0)
	err := p.enginer.Where("username=? and channelId=?",username,channelId).Find(&accountDatas)
	if err != nil{
		logger.Log.Errorf("GetAccountDataByUsernameAndChannelId failed, error:%s",err.Error())
		return nil,err
	}

	if len(accountDatas) == 0 {
		return nil,nil
	}

	return accountDatas,nil
}

func (p *accountDataDao) GetAccountDataByAccountId(accountId int64,appId string) (*pojo.AccountData,error) {
	accountData := &pojo.AccountData{}
	b,err := p.enginer.Where("accountId =? and appId =?",accountId,appId).Get(accountData)
	if err != nil {
		logger.Log.Errorf("[AccountDataDao] GetAccountDataByAccountId failed,error:%s",err.Error())
		return nil,err
	}

	if !b {
		return nil,nil
	}

	return accountData, nil
}